package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysSecurity;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysConfigService configService;

    @Value("${token.soloLogin}")
    private boolean soloLogin;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关
        if (captchaOnOff) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        //错误次数
        int i = 0;
        String redisKey = Constants.SYS_LOGINERRORNUM + username;
        try {
            //存redis统计密码错误次数
            if (redisCache.getCacheObject(redisKey) == null) {
                redisCache.setCacheObject(redisKey, i, 5, TimeUnit.MINUTES);
            } else {
                i = Integer.parseInt(redisCache.getCacheObject(redisKey).toString());
            }
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                //密码错误次数过多将被锁定
                Object cacheObject = redisCache.getCacheObject(redisKey);
                if(cacheObject != null)
                {
                    i = Integer.parseInt(cacheObject.toString());
                }
                i++;
                redisCache.setCacheObject(redisKey, i);
                SysUser user = userService.selectUserByUserName(username);
                if (user != null && user.getSysSecurity() != null) {
                    if (user.getSysSecurity().getPwdErrorNum() != null && user.getSysSecurity().getPwdIsError()) {
                        Object newValue = redisCache.getCacheObject(redisKey);
                        if (Integer.parseInt(newValue.toString()) >= user.getSysSecurity().getPwdErrorNum()) {
                            //锁定账号
                            user.setLocked("1");
                            //更新锁定状态
                            userService.updateUser(user);
                            //获取锁定时间 默认五分钟，五分钟内不允许登录
                            int lockTime = 5;
                            if (user.getSysSecurity().getPwdErrorTime() != null) {
                                lockTime = user.getSysSecurity().getPwdErrorTime();
                            }
                            //锁定账号后，五分钟内不允许登录
                            redisCache.setCacheObject(Constants.SYS_LOGINLOCK + username, username, lockTime, TimeUnit.MINUTES);
                            throw new ServiceException("用户账号已被锁定，请在" + lockTime + "分钟后重试或联系管理员！");
                        }
                    }

                }
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        //清楚redis错误次数
        if(redisCache.getCacheObject(redisKey) != null)
        {
            redisCache.deleteObject(redisKey);
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 判断是否允许账户多终端同时登录
        if(redisCache.getCacheObject(Constants.SECURITY_SETTING+loginUser.getUserId()) != null)
        {
            SysSecurity sysSecurity = (SysSecurity)redisCache.getCacheObject(Constants.SECURITY_SETTING+loginUser.getUserId());
            if (sysSecurity != null && sysSecurity.getSingleLogin() != null) {
                soloLogin = sysSecurity.getSingleLogin();
            }
            if (!soloLogin) {
                // 如果用户不允许多终端同时登录，清除缓存信息
                String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
                String userKey = redisCache.getCacheObject(userIdKey);
                if (StringUtils.isNotEmpty(userKey)) {
                    redisCache.deleteObject(userIdKey);
                    redisCache.deleteObject(userKey);
                }
            }
        }
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new CaptchaException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
